package com.persistencia.util;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;


import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.exceptions.PersistenceException;
import com.thoughtworks.xstream.XStream;

/**
 * The Class UtilXml, to write/read from the file xml.
 */
public class RecordXml extends RecordStrategy {

	/** The xstream. */
	private XStream xstream;

	public RecordXml(Class<?> classType) throws PersistenceException {
		super(classType);
		try {
			xstream = new XStream();
			FILE_NAME += getClassTypeName() + ".xml";
			createFile();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}
	}

	@Override
	public synchronized Boolean writeData(List<?> obj)
			throws PersistenceException {
		// TODO revisar la mejor forma de sincronizar
		Document document = null;
		try {
			String xml = xstream.toXML(obj);
			document = DocumentHelper.parseText(xml);
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(new FileWriter(FILE_NAME), format);
			writer.write(document);
			writer.close();
		} catch (Exception e) {
			throw new PersistenceException(e);
		}

		return true;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public synchronized List<?> readData() throws PersistenceException {
		// TODO revisar la mejor forma de sincronizar


		List<Object> list = new ArrayList<Object>();

		try {
			File file = new File(FILE_NAME);
			list = (List<Object>) xstream.fromXML(file);
			return list;

		} catch (Exception e) {
			throw new PersistenceException(e);
		}

	}

}
